const await = require('await-stream-ready/lib/await');

const Service = require('egg').Service;

class WechatService extends Service {
    /**
     * @param {提交的数据} data 
     * @return 1，0
     */
    async getopenid(code, appId, appSecret) {
        const { config } = this;
        appId = appId || config.wechat.appId;
        appSecret = appSecret || config.wechat.appSecret;
        let https = require('https');
        let url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appId + "&secret=" + appSecret + "&js_code=" + code + "&grant_type=authorization_code";
        console.log("getopenid====", url);
        return new Promise(function (resolve, reject) {
            https.get(url, (res) => {
                res.setEncoding('utf8');
                let rawData = '';
                res.on('data', (chunk) => rawData += chunk);

                res.on('end', () => {
                    resolve(rawData);
                });
            });
        });
    }

    /**
     * 通过code获取网页授权access_token
     * @param {*} appId 
     * @param {*} appSecret 
     */
    async getAccessTokenByCode(appId, appSecret) {
        const { config,ctx,app } = this;
        appId = appId || config.wechat.appId;
        appSecret = appSecret || config.wechat.appSecret;
        console.log("app.utils.axios============",app.utils.axios);
        let rs = await app.utils.axios.request("GET",`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appId}&secret=${appSecret}`);
        return rs;
    }


}

module.exports = WechatService;